<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*  
            ①：多棵树组成数组的简单遍历法
            let tree = [
                {
                    val: 1,
                    children: [
                        { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                        { val: 3, children: [{ val: 8 }] },
                        { val: 4 },
                    ],
                },
            ]
            let res = []
            function preOrder(tree) {
                tree.forEach((item) => {
                    res.push(item.val)
                    let children = item.children || []
                    if (children) {
                        preOrder(children)
                    }
                })
            }
            preOrder(tree)
            console.log(res) */

            /* ②单棵数的先序遍历   总结来看，二叉树本质上就是特殊的多叉树，只不过把forEach遍历children，直接写死成左右子节点而已 */
            /*       let tree = {
                val: 1,
                children: [
                    { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                    { val: 3, children: [{ val: 8 }] },
                    { val: 4 },
                ],
            } */
            function fn(root) {
                let res = []
                if (!root) return res
                function preOrder(root) {
                    if (!root) return
                    res.push(root)
                    let children = root.children || []
                    for (let i = 0; i < children.length; i++) {
                        preOrder(children[i])
                    }
                }
                preOrder(root)
                return res
            }

            /* 如果有多个根节点，还可以这样写,说白了就是第一次的时候遍历三棵树 */
            let doubleTree = [
                {
                    val: 1,
                    children: [
                        { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                        { val: 3, children: [{ val: 8 }] },
                        { val: 4 },
                    ],
                },
                {
                    val: 1,
                    children: [
                        { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                        { val: 3, children: [{ val: 8 }] },
                        { val: 4 },
                    ],
                },
            ]
            let result = []
            doubleTree.forEach((root) => {
                result.push(...fn(root))
            })
            console.log(result)
        </script>
    </body>
</html>
